package ctrl.action.impl;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Model;
import model.beans.ClientBean;

import util.ProjectConstants;

import ctrl.action.ServletAction;

public class LoginServletAction implements ServletAction{
	
	private ServletContext context;	
	public LoginServletAction(ServletContext context) {
		this.context = context;
	}
	
	@Override
	public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		
		String jsp = null;
		String jspRedirect = null;
		Model model = (Model)context.getAttribute(ProjectConstants.PARAMMODEL);
		HttpSession session = request.getSession();
		String username = request.getParameter(ProjectConstants.PARAMUSERNAME);
		String password = request.getParameter(ProjectConstants.PARAMPASSWORD);

		if(request.getParameter(ProjectConstants.PARAMSIGNIN) != null){
			request.setAttribute(ProjectConstants.PARAMUSERNAME, username);
			request.setAttribute(ProjectConstants.PARAMPASSWORD, password);

			if(username != null && password != null){
				ClientBean user = (ClientBean)model.getClient(username, password);
				if(user != null){					
					session.setAttribute(ProjectConstants.PARAMUSER, user);	
					
					//Redirect to the previous page
					jspRedirect = (String)session.getAttribute(ProjectConstants.PARAMPREVIOUSPAGE);
				}
				else{
					request.setAttribute(ProjectConstants.PARAMINVALIDINFO, "Invalid Information!");
					jsp = ProjectConstants.PAGELOGIN;
				}
				
			}
			else{			
				session.setAttribute(ProjectConstants.PARAMINVALIDINFO, "Invalid Information!");
				jsp = ProjectConstants.PAGELOGIN;
			}
		}
		else{
			jsp = ProjectConstants.PAGELOGIN;
		}
		
		if(jsp != null){
			context.getRequestDispatcher("/" + jsp + ".jspx").forward(request, response);
		}
		else{
			response.sendRedirect(context.getContextPath()+"/"+ jspRedirect);
		}
	}
}
